package com.travel.config;

import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Configuration
public class RedissonConfig {

    @Lazy
    @Autowired
    private StringRedisTemplate redisTemplate;


    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        // 单机模式，根据实际情况修改 Redis 地址
        config.useSingleServer()
              .setAddress("redis://127.0.0.1:6379")
              .setDatabase(0) // 选择数据库
              .setConnectionMinimumIdleSize(5) // 最小空闲连接数
              .setConnectionPoolSize(20); // 连接池大小
        
        return Redisson.create(config);
    }

    /**
     * 定义一个布隆过滤器的Bean对象
     */

    @Bean
    public RBloomFilter rBloomFilter(RedissonClient redissonClient) {
        // 1.分布式的布隆过滤器
        RBloomFilter<Object> albumBloomFilter = redissonClient.getBloomFilter("albumIdBloomFilter");
        // 添加本地锁或者分布式锁可以（就算多个实例  那么布隆过滤器也只会初始化一次）
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("lock:bloomFilter", "1");
        if (aBoolean) {
            // 2.对布隆进行初始化操作
            boolean b = albumBloomFilter.tryInit(1000000, 0.0001);
            logger.info("分布式布隆过滤器初始化{}", b ? "成功" : "失败");
        }
        return albumBloomFilter;
    }
}